import qiniu from './qiniuSdk'
import api from './api'

const UPLOAD = {
  domain: ''  // TODO 这里的域名要变
}
const weappUpload = {
  uploadFile: function (filePath, options) {
    return new Promise((resolve, reject) => {
      qiniu.upload(filePath, res => {
        resolve(res)
      }, error => {
        reject(error)
      }, options)
    })
  },
  uploadImg: async function (filePath) {
    console.log(filePath)
    let res = await api.getToken()
    const { success, data } = res
    if (success) {
      let uploadRes = await this.uploadFile(filePath, {
        region: 'EAST2', //'ECN', // 'EAST2',
        key: filePath.split('//')[1],
        uptoken: data?.uptoken
      })
      console.log(uploadRes, 'uploadRes')
      // 长宽是否旋转
      const isRotate = uploadRes?.tags?.rotate
      if (uploadRes.hasOwnProperty('imageURL')) {
        return {
          path: `${UPLOAD.domain}${uploadRes.path}`,
          width: isRotate ? uploadRes.height : uploadRes.width,
          height: isRotate ? uploadRes.width : uploadRes.height,
          duration: uploadRes.duration
        }
      }
      return false
    } else {
      console.log(res.status.msg)
      return false
    }
  }
}

export default weappUpload
